import { craeteEffect, effectTypes } from './helper'
import isPromise from 'is-promise'

/**
 * 提供一个函数，用于产生apply effect 
 * @export
 * @param {*} context this指向
 * @param {function} fn 
 * @param {Array} args
 * @return {*} 
 */
export function apply(context, fn, args = []) {
    return craeteEffect(effectTypes.APPLY, { context, fn, args })
}

/**
 * 处理apply effect 
 * @export
 * @param {*} env
 * @param {*} effect
 * @param {*} next
 */
export function runApplyEffect(env, effect, next) {
    const { store } = env
    const { payload: { context, fn, args } } = effect

    const result = fn.apply(context, args)
    if (isPromise(result)) {
        result.then(r => next(r), err => next(null, err))
    } else {
        next(result)
    }


}